import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 定义被积函数
def integrand(t):
    return np.sqrt(t) * (t - 1)  # 正确对应 √t * (t-1)

# 定义原函数 f(x) = ∫₀ˣ² √t (t-1) dt
def f(x):
    result, _ = quad(integrand, 0, x**2)
    return result

# 定义导数函数 f'(x) = 2x * |x| * (x² - 1)（基于手动求解结果）
def f_prime(x):
    return 2 * x * np.abs(x) * (x**2 - 1)

# 生成 x 值范围（覆盖临界点 -1, 0, 1）
x_vals = np.linspace(-2, 2, 500)
y_vals = [f(x) for x in x_vals]
dy_vals = [f_prime(x) for x in x_vals]  # 计算导数值

# 创建图形和子图
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))

# 绘制函数图像
ax1.plot(x_vals, y_vals, 'b-', linewidth=2, label='f(x)')
ax1.set_xlabel('x')
ax1.set_ylabel('f(x)')
ax1.set_title(r'函数 f(x) = $\int_{0}^{x^2}\sqrt{t}(t-1)dt$ 的图像') 
ax1.grid(True)
ax1.legend()

# 标记临界点（导数为零的点）
critical_points = [-1, 0, 1]
for cp in critical_points:
    ax1.axvline(x=cp, color='red', linestyle='--', alpha=0.7, label=f'临界点 x={cp}')
ax1.legend()

# 绘制导数图像
ax2.plot(x_vals, dy_vals, 'r-', linewidth=2, label="f'(x)")
ax2.axhline(y=0, color='k', linestyle='-', alpha=0.3)
ax2.set_xlabel('x')
ax2.set_ylabel("f'(x)")
ax2.set_title("导数 $f'(x) = 2x·|x|·(x^2-1)$ 的图像")
ax2.grid(True)
ax2.legend()

# 标记导数零点
for cp in critical_points:
    ax2.axvline(x=cp, color='red', linestyle='--', alpha=0.7)
    ax2.plot(cp, 0, 'ro', markersize=5)  # 标记临界点

plt.tight_layout()
plt.show()

# 分析单调区间和极值点
print("=" * 50)
print("单调区间和极值点分析")
print("=" * 50)

# 临界点
print(f"临界点: x = {critical_points}")

# 测试各区间导数的符号
intervals = [(-np.inf, -1), (-1, 0), (0, 1), (1, np.inf)]
test_points = [-1.5, -0.5, 0.5, 1.5]  # 每个区间内的测试点

print("\n单调性分析:")
for i, point in enumerate(test_points):
    deriv_val = f_prime(point)
    sign = "+" if deriv_val > 0 else "-" if deriv_val < 0 else "0"
    monotonicity = "递增" if deriv_val > 0 else "递减"
    print(f"  区间 {intervals[i]}: f'({point}) = {deriv_val:.2f} ({sign}) → 函数单调{monotonicity}")

print("\n极值点分析:")
print("  x = -1: 导数符号由负变正 → 极小值点")
print("  x =  0: 导数符号由正变负 → 极大值点")
print("  x =  1: 导数符号由负变正 → 极小值点")

# 验证临界点处的函数值
print("\n极值点函数值:")
for cp in critical_points:
    y_val = f(cp)
    print(f"  f({cp}) = {y_val:.4f}")